import React, { Component, PropTypes } from 'react';
import { noop, isFunction } from 'lodash';

import TabItem from './tab-item.jsx';

/**
 * Tabs
 * @class {Tabs}
 * @extends {React.Component}
 */
export default class Tabs extends Component {

    static propTypes = {
        /**
         * 当前选中项
         * @type {number|string}
         */
        selectedIndex: PropTypes.number,

        /**
         * 激活标签事件处理
         * @type {TabItem}
         */
        onSelect: PropTypes.func,

        /**
         * 关闭标签事件处理
         * @type {TabItem}
         */
        onClose: PropTypes.func,

        /**
         * 标签页元素
         * @type {Object[]}
         */
        items: PropTypes.array,

        /**
         * 是否允许关闭
         * @type {boolean}
         */
        closable: PropTypes.bool
    };

    render() {
        const { children, onSelect, onClose, selectedIndex, items, closable } = this.props;

        return (
            <div className="tabs">
                {items.map((item, index) => (
                    <TabItem key={item.path}
                        active={selectedIndex === index}
                        modified={item.dirty}
                        closable={closable}
                        label={item.name}
                        onSelect={() => {
                            if (isFunction(onSelect)) {
                                onSelect(index)
                            }
                        }}
                        onClose={(event) => {
                            event.stopPropagation();

                            const dirty = item.dirty;

                            if (isFunction(onSelect)) {
                                if (dirty) {
                                    const result = confirm(`Do you want to close the tab?`);
                                    if(result) {
                                        onClose(index);
                                    }
                                } else {
                                        onClose(index);
                                }
                            }
                        }} />
                ))}
            </div>
        );
    }
}